<template>
    <myDialog :visible="popupFlag" @close="closeHandle">
        <div style="padding: 100px 0;">
            <!-- <myPopupView :visible="popupFlag" @close="closeHandle"> -->
            <div class="editBox" @click.stop>
                <div class="header flex">
                    <div class="title">{{ title }}</div>
                    <img @click="closeHandle" src="../../assets/pauTypeClose.png">
                </div>
                <div class="formBox">
                    <el-form :model="chargeTaskForm" ref="chargeTaskRef" :rules="chargeTaskrules" label-position="left"
                        label-width="100px">
                        <el-form-item label="收费形式" prop="type">
                            <el-select v-if="user.campus == 1" v-model="chargeTaskForm.type" clearable
                                placeholder="请选择收费形式" @change="changeCampus">
                                <el-option v-for="(item, index) in payNameData" :key="index" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-select v-if="user.campus == 2" v-model="chargeTaskForm.type" clearable
                                @change="changeCampus" placeholder="请选择收费形式">
                                <el-option v-for="(item, index) in payNameData1" :key="index" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="年级名称" prop="gradeId">
                            <el-select v-model="chargeTaskForm.gradeId" clearable placeholder="请选择年级"
                                @change="chageGradeId">
                                <el-option v-for="item in timeData" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="收费类型" prop="payType">
                            <el-select v-model="chargeTaskForm.payType" clearable placeholder="请选择收费类型">
                                <el-option key="1" :value="1" label="学校收费"></el-option>
                                <el-option key="2" :value="2" label="代收费用"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="缴费时间" prop="publishTimeStr">
                            <ElConfigProvider :locale="locale">
                                <el-date-picker v-model="chargeTaskForm.publishTimeStr" type="datetime"
                                    :disabled-time="disabledTime" :disabled-date="disabledDate" placeholder="请选择缴费时间"
                                    format="YYYY/MM/DD HH:mm:ss" style="width: 100%;" @change="changeTime"
                                    @focus="focusTimeHandle" />
                            </ElConfigProvider>
                        </el-form-item>
                        <el-form-item label="缴费任务" prop="name">
                            <el-input v-model="chargeTaskForm.name" placeholder="请输入缴费任务" />
                        </el-form-item>
                        <el-form-item label="收费项目" prop="paymentTypeIds">
                            <div class="type_box">
                                <div :class="{
        'typeBox': true, 'typeBox_active': isSelected(item.id)
    }" v-for="item in paymentTypeList" :key="item.id" @click="addChecked(item)">{{ item.name }}
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item :label="item.paymentTypeName" prop="" v-for="(item, index) in checkedData"
                            :key="index">
                            <div class="checke flex">
                                <el-input-number v-model="item.paymentAmount" controls-position="right" :step="0.01"
                                    :min="0" style="margin-right: 15px;" :disabled="item.flag">
                                    <template #decrease-icon>
                                        <el-icon @click="Number(item.paymentAmount) + 0.01">
                                            <Minus />
                                        </el-icon>
                                    </template>
                                    <template #increase-icon>
                                        <el-icon @click="Number(item.paymentAmount) - 0.01">
                                            <Plus />
                                        </el-icon>
                                    </template>
                                </el-input-number>
                                <el-checkbox v-model="item.flag" label="自定义缴费" @change="changeCheckbox(index)" />
                            </div>
                        </el-form-item>
                    </el-form>
                </div>

                <div style="width: 10px; height: 80px;"></div>
                <div class="btnBox">
                    <el-button class="btn1" @click="closeHandle">取消</el-button>
                    <el-button class="btn2" v-loading.fullscreen.lock="fullscreenLoading" @click="save">确认</el-button>
                </div>
            </div>
            <!-- </myPopupView> -->
        </div>
    </myDialog>
</template>

<script>
import myPopupView from "@/components/commonModule/myPopupView.vue";
import { httpService } from "@/utils/httpService";
import { formatTime, formatTime1, getGradeIds } from "@/utils/dateFormat";
import { ElConfigProvider, ElMessage, ElForm } from "element-plus";
import { vxRule } from "@/utils/validator";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { Minus, Plus, } from "@element-plus/icons-vue";
import myDialog from "../commonModule/myDialog.vue";
import { API_BASE_NAME, API_BASE_NAME1 } from "../../constants"

export default {

    data() {
        return {
            schoolName: API_BASE_NAME,
            schoolName1: API_BASE_NAME1,
            queryData: {},
            approveData: [],
            popupFlag: false,
            title: "",
            btnFlag: false,
            paymentTypeList: [],
            minTime: "",
            payNameData: [
                {
                    label: "非税收费",
                    value: 1,
                },
                {
                    label: "微信收费",
                    value: 2,
                },
                {
                    label: "东校区非税收费",
                    value: 3,
                }
            ],
            payNameData1: [
                {
                    label: "非税收费",
                    value: 1,
                },
                {
                    label: "微信收费",
                    value: 2,
                },
                {
                    label: "校本部非税收费",
                    value: 3,
                },
            ],
            user: {},
            checkedData: [],
            timeData: getGradeIds(),
            fullscreenLoading: false,
            nameData: {
                campusName: "",
                gradeId: '',
                typeName: "",
                date: "",
            },
            chargeTaskForm: {
                id: "",
                name: "",
                gradeId: "",
                payType: "",
                type: "",
                publishTimeStr: "",
                paymentTypeIds: [],
                num: 0,
                radio: "",
            },
            chargeTaskrules: {
                name: vxRule(true, null, "blur"),
                type: vxRule(true, null, "blur"),
                paymentTypeIds: vxRule(true, null, "blur"),
                gradeId: vxRule(true, null, "blur"),
                publishTimeStr: vxRule(true, null, "blur"),
                payType: vxRule(true, null, "blur"),
            },

        };
    },
    components: {
        myPopupView, ElConfigProvider, Minus, Plus, myDialog
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    watch: {
        nameData: {
            handler(newValue) {
                this.chargeTaskForm.name = `${newValue.campusName}${newValue.gradeId}${newValue.typeName}${newValue.date}`
                // console.log(12312, this.chargeTaskForm.name);
            },
            deep: true,
        }
    },
    mounted() {
        this.user = JSON.parse(sessionStorage.getItem('user'))
        this.user.campus == 1 ? this.nameData.campusName = this.schoolName : this.nameData.campusName = this.schoolName1
        // console.log(this.nameData.campusName);
        // this.disabledBeforeCurrentTime()
        this.getdateName()
        this.getpaymentTypeList()

    },
    methods: {
        closeHandle() {
            this.popupFlag = false
            this.clear()
        },
        changeCheckbox(index) {
            this.checkedData[index].paymentAmount = 0
        },
        getdateName() {
            this.user.campus == 1 ? this.nameData.campusName = this.schoolName : this.nameData.campusName = this.schoolName1
            let date = new Date();
            let nowYear = date.getFullYear()
            let nowMonth = date.getMonth() + 1
            let nowDay = date.getDate()

            nowMonth >= 10 ? nowMonth : nowMonth = `0${nowMonth}`
            nowDay >= 10 ? nowDay : nowDay = `0${nowDay}`
            this.nameData.date = `${nowMonth}${nowDay}`

        },
        changeCampus(value) {
            if (this.user.campus == 1 && value == 3) {
                this.nameData.campusName = this.schoolName1
            } else if (this.user.campus == 1 && value != 3) {
                this.nameData.campusName = this.schoolName
            } else if (this.user.campus == 2 && value != 3) {
                this.nameData.campusName = this.schoolName1
            } else if (this.user.campus == 2 && value == 3) {
                this.nameData.campusName = this.schoolName
            }
        },
        chageGradeId(value) {
            this.nameData.gradeId = value
        },
        disabledDate(time) {
            const halfHourLater = new Date(Date.now() + 30 * 60 * 1000);
            return time.getTime() < halfHourLater.setHours(0, 0, 0, 0);
        },
        getHalfHourLater() {
            const now = new Date();
            const halfHourLater = new Date(now.getTime() + 30 * 60 * 1000);
            return formatTime1(halfHourLater);
        },
        disabledTime(time) {
            const halfHourLater = new Date(Date.now() + 30 * 60 * 1000);
            const selectedDate = new Date(time);

            if (
                selectedDate.getFullYear() === halfHourLater.getFullYear() &&
                selectedDate.getMonth() === halfHourLater.getMonth() &&
                selectedDate.getDate() === halfHourLater.getDate()
            ) {
                const limitHour = halfHourLater.getHours();
                const limitMinute = halfHourLater.getMinutes();
                const limitSecond = halfHourLater.getSeconds();

                return (
                    selectedDate.getHours() < limitHour ||
                    (selectedDate.getHours() === limitHour &&
                        selectedDate.getMinutes() < limitMinute) ||
                    (selectedDate.getHours() === limitHour &&
                        selectedDate.getMinutes() === limitMinute &&
                        selectedDate.getSeconds() < limitSecond)
                );
            }

            return false;
        },


        focusTimeHandle() {
            const now = new Date(); // 当前时间
            const future = new Date(now.getTime() + 35 * 60000);
            this.chargeTaskForm.publishTimeStr = formatTime1(future)
        },

        changeTime(value) {
            if (formatTime1(value) < this.getHalfHourLater()) {
                ElMessage.error("最小选择时间为当前时间半小时后");
                this.chargeTaskForm.publishTimeStr = ""
            } else {
                this.chargeTaskForm.publishTimeStr = formatTime1(new Date(value))
                const date = new Date(value)
                let nowMonth = date.getMonth() + 1
                let nowDay = date.getDate()
                this.nameData.date = `${nowMonth}${nowDay}`
            }
        },
        isSelected(id) {
            const index = this.checkedData.find(item => item.paymentTypeId == id);
            if (index) {
                return true
            } else {
                return false
            }
        },
        addChecked(data) {

            const idIndex = this.chargeTaskForm.paymentTypeIds.indexOf(data.id);
            const index = this.checkedData.findIndex(item => item.paymentTypeId === data.id);

            if (index === -1) {
                this.checkedData.push({ paymentTypeId: data.id, paymentTypeName: data.name, paymentAmount: 0, flag: false });
            } else {
                this.checkedData.splice(index, 1);
            }
            if (idIndex === -1) {
                this.chargeTaskForm.paymentTypeIds.push(data.id);
            } else {
                this.chargeTaskForm.paymentTypeIds.splice(index, 1);
            }

            this.nameData.typeName = this.checkedData.map(item => item = item.paymentTypeName).join("")

        },
        getpaymentTypeList() {
            httpService(
                "/javaApi/paymentType/list/1/10", {}, "get"
            ).then((data) => {
                this.paymentTypeList = data.list.sort((a, b) => b.sortNum - a.sortNum);
            });
        },
        clear() {
            this.chargeTaskForm.name = ""
            this.chargeTaskForm.gradeId = ""
            this.chargeTaskForm.payType = ""
            this.chargeTaskForm.type = ""
            this.chargeTaskForm.publishTimeStr = ""
            this.chargeTaskForm.paymentTypeIds = []
            this.chargeTaskForm.num = 0
            this.chargeTaskForm.radio = ""

            this.popupFlag = false
            this.title = ""

            this.nameData.campusName = ""
            this.nameData.gradeId = ''
            this.nameData.typeName = ""
            this.nameData.date = ""
            this.checkedData = []
        },
        save() {
            this.$refs.chargeTaskRef.validate((valid) => {
                if (valid) {
                    let num = 0
                    for (let index = 0; index < this.checkedData.length; index++) {
                        if (this.checkedData[index].flag == false && this.checkedData[index].paymentAmount <= 0) {
                            num += 1
                            ElMessage.error(this.checkedData[index].paymentTypeName + "金额不能小于0");
                            break
                        }
                    }
                    if (num > 0) {
                        return
                    }

                    let type = ""
                    let moneyFlow = ""
                    if (this.user.campus == 1 && this.chargeTaskForm.type == 3) {
                        type = 1
                        moneyFlow = 2
                    } else if (this.user.campus == 1 && this.chargeTaskForm.type != 3) {
                        type = this.chargeTaskForm.type
                        moneyFlow = 1
                    } else if (this.user.campus == 2 && this.chargeTaskForm.type == 3) {
                        type = 1
                        moneyFlow = 1
                    } else if (this.user.campus == 2 && this.chargeTaskForm.type != 3) {
                        type = this.chargeTaskForm.type
                        moneyFlow = 2
                    }




                    this.fullscreenLoading = true
                    this.checkedData = this.checkedData.map(item => {
                        return item = { paymentTypeId: item.paymentTypeId, paymentTypeName: item.paymentTypeName, paymentAmount: item.paymentAmount, }
                    })

                    let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
                    params.append("name", this.chargeTaskForm.name);
                    params.append("gradeId", this.chargeTaskForm.gradeId);
                    params.append("payType", this.chargeTaskForm.payType);
                    params.append("type", type);
                    params.append("publishTimeStr", this.chargeTaskForm.publishTimeStr);
                    params.append("moneyFlow", moneyFlow);
                    params.append("json", JSON.stringify(this.checkedData));
                    params.append("campus", this.user.campus);
                    // console.log(this.chargeTaskForm.name);

                    if (this.chargeTaskForm.id) {
                        params.append("id", this.chargeTaskForm.id);
                        httpService("/javaApi/paymentType/edit", params, "post").then(
                            (data) => {
                                this.fullscreenLoading = false
                                if (data.code == 200) {
                                    ElMessage.success("修改成功");
                                    this.clear();
                                    //刷新父组件的数据
                                    this.$emit("refreshHandle")
                                } else {
                                    ElMessage.error("修改失败");
                                }
                            }
                        );
                    } else {
                        httpService("/javaApi/payment/add", params, "post").then(
                            (data) => {
                                this.fullscreenLoading = false
                                if (data.code == 200) {
                                    ElMessage.success("添加成功");
                                    this.clear();
                                    //刷新父组件的数据
                                    this.$emit("refreshHandle")
                                } else {
                                    ElMessage.error("添加失败");
                                }
                            }
                        );
                    }
                } else {
                    return false;
                }
            });
        },
    }
}
</script>

<style scoped>
/* * {
    margin: 0;
    padding: 0;
} */

.flex {
    display: flex;
    align-items: center;
}

.editBox {
    width: 666px;
    min-height: 469px;
    border-radius: 5px;
    background-color: #fff;
    position: relative;
}

.header {
    height: 64px;
    background: url(../../assets/payType_headerBg.png) no-repeat;
    background-size: cover;
    padding: 0 25px;
    justify-content: space-between
}

.title {
    color: #000;
    font-size: 18px;
    line-height: 18px;
    /* font-weight: bold;  */
}

.formBox {
    padding: 25px 35px 0 20px;
}

.el-form-item {
    margin-bottom: 15px;
}

.lel-form-item__label {
    text-align: left !important;
}

.btnBox {
    position: absolute;
    bottom: 5px;
    right: 35px;
    float: right;
    /* margin-top: 30px; */
    /* margin-right: 35px; */
    padding-bottom: 15px;
}

.btnBox button {
    width: 97px;
    height: 35px;
    border-radius: 5px;
    font-size: 14px;
    margin-left: 10px;
}

.btn1 {
    border: 1px solid #007EFF;
    color: #007EFF;
    background-color: #0080ff15
}

.btn2 {
    background-color: #007EFF;
    border: none;
    color: #fff;
}

.typeBox {
    height: 35px;
    line-height: 35px;
    background-color: #fff;
    /* margin: 0 0px 5px 0; */
    border: 1px solid #DEE1E5;
    border-radius: 5px;
    font-size: 14px;
    color: #666;
    text-align: center;
    cursor: pointer;
}

.typeBox_active {
    height: 35px;
    line-height: 35px;
    background: url(../../assets/payTypeOk.png) no-repeat;
    background-position: bottom right;
    background-color: #fff;
    /* margin: 0 0px 5px 0; */
    border: 1px solid #007EFF;
    border-radius: 5px;
    font-size: 14px;
    text-align: center;
    color: #666;
    overflow: hidden;
    box-sizing: border-box;
    cursor: pointer;
}


.type_box {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
}

.checkedBox {
    margin-top: 10px;
}

.el-checkbox {
    /* margin: 0 15px; */
}

.payBtnBox button {
    width: 80px;
    height: 30px;
    border-radius: 5px;
    border: none;
    margin-left: 10px;
}

.downBtn {
    background-color: #007EFF;
    color: #fff;
    border-radius: 8px;
    border: none;
}

.fileBtn {
    background-color: #00c78c;
    color: #fff;
    border-radius: 8px;
    border: none;
}

.uploadBtn {
    background-color: #FF7200;
    border-radius: 8px;
    color: #fff;
    border: none;
}
</style>